package com.example.zhongxinjinqiao.myapplication.device;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.zhongxinjinqiao.myapplication.R;
import com.example.zhongxinjinqiao.myapplication.card.model.DeviceModel;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.beacon.BeaconParser;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothLog;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 *
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private ListView listView;
    private List<DeviceModel> models = new ArrayList<DeviceModel> ();
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private BluetoothClient mClient;



    public HomeFragment() {
        // Required empty public constructor
    }

    private  void callCard(DeviceModel model){
        Log.i ( "","--->呼叫卡片" );
    }

    /** 
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated ( savedInstanceState );
        listView = getActivity ().findViewById ( R.id.listView);

        for (int i = 0; i < 30; i++){
            DeviceModel model = new DeviceModel ();
            model.name = String.valueOf ( i );
            models.add ( model );
        }
        setAdapter ();
        mClient = new BluetoothClient(this.getActivity ());
        searchDevice ();

    }

    private void searchDevice() {
        SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(3000, 3)   // 先扫BLE设备3次，每次3s
                .searchBluetoothClassicDevice(5000) // 再扫经典蓝牙5s
                .searchBluetoothLeDevice(2000)      // 再扫BLE设备2s
                .build();

        mClient.search(request, new SearchResponse () {
            @Override
            public void onSearchStarted() {

            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                Beacon beacon = new Beacon(device.scanRecord);

                if (device.device.getName () != null && device.device.getName ().contains ( "iQ_098C" )) {
                    Log.v ( "", device.device.getName () );
                    BeaconParser parser = new BeaconParser ( beacon.mItems.get ( 0 ) );
                    Log.v ( "",  String.valueOf ( parser.readByte () ) );
                    Log.v ( "",  String.valueOf (  parser.readShort ()) );
                    BluetoothLog.v(String.format("beacon for %s\n%s", device.getAddress(), beacon.toString()));
                }



            }


            @Override
            public void onSearchStopped() {

            }

            @Override
            public void onSearchCanceled() {

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    public void setAdapter() {
        BaseAdapter adapter = new BaseAdapter () {
            @Override
            public int getCount() {
                return models.size ();
            }

            @Override
            public Object getItem(int i) {
                return null;
            }

            @Override
            public long getItemId(int i) {
                return 0;
            }

            @Override
            public View getView(final int i, View view, ViewGroup viewGroup) {
                DeviceItemHolder holder;
                if (view == null) {
                    holder = new DeviceItemHolder(getActivity ());
                }
                else {
                    holder = (DeviceItemHolder)view;
                }

                holder.callBtn.setOnClickListener ( new View.OnClickListener () {
                    @Override
                    public void onClick(View view) {
                        callCard (  models.get ( i ));
                    }
                } );
                holder.name.setText ( models.get ( i ).name );
                return holder;
            }
        };



        listView.setAdapter ( adapter );
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.i ("点击第","--->"+String.valueOf ( i ) + String.valueOf ( l ));

                Intent intent = new Intent("logout");
                DeviceModel model = new DeviceModel ();
                model.name = "测试";
                model.deviceId = 10;
                intent.putExtra ( "device", model );

                getActivity().sendBroadcast(intent);

                intent = new Intent ( getActivity (), DeviceStatusActivity.class );

                getActivity ().startActivity ( intent );
            }
        });

    }

     class DeviceItemHolder extends ConstraintLayout {
        ImageView img;
        TextView name;
        TextView distance;
        TextView power;
        Button callBtn;
        DeviceModel model;

        public DeviceModel getModel() {
            return model;
        }

        public void setModel(DeviceModel model) {
            this.model = model;
            this.name.setText ( "hello" );
        }

         @Override
         protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
             super.onLayout ( b, i, i1, i2, i3 );
         }

         @Override
         protected void onFinishInflate() {
             super.onFinishInflate ();
         }

         public DeviceItemHolder(Context context, AttributeSet attrs) {
             super ( context, attrs );
         }

         public DeviceItemHolder(Context context) {
             super ( context );
             LayoutInflater.from(context).inflate ( R.layout.device_item, this );
             this.img = findViewById ( R.id.imageView2 );
             this.name = findViewById ( R.id.device_name);
             this.distance = findViewById ( R.id.device_distance );
             this.power = findViewById ( R.id.device_power );
             this.callBtn = findViewById ( R.id.callButton );
         }
     }
}

